/**
 * 移动端路由
 * 重写了路由部分方法，使其适配移动端
 */
import store from '@/store'

function getPath(location) {
  if (typeof location === 'string') {
    const queryIndex = location.indexOf('?')
    if (queryIndex >= 0) {
      return location.slice(0, queryIndex)
    }
    return location
  }
  if (typeof location === 'object') {
    return location.path
  }
  return null
}

export default {
  initRouter(Router, tabbar, tabbar2, tabbar3) {
    const mRouter = store.state.mRouter;
    // 修改Router本身的push
    let lPush = Router.prototype.push;
    tabbar = [...tabbar, ...tabbar2, ...tabbar3];
    Router.prototype.push = function (location, onComplete, onAbort) {
      let lGoCount = this.havRouterHistory(location);
      const toPath = getPath(location);
      const fromPath = this.currentRoute.path;

      //判断是否由一个tabbar页跳转另外一个tabbar
      const isTabbar2Tabbar =
        tabbar.some((item) => item.path === toPath) &&
        tabbar.some((item) => item.path === fromPath);
      if (isTabbar2Tabbar) {
        store.commit("mRouter/setDirection", "none");
        store.commit("mRouter/clearHistoryRouter");
        let lReplace = Router.prototype.replace;
        lReplace.call(this, location, onComplete, onAbort);
        return;
      }
      //-1的时候是不是返回，要跳转新页面
      if (lGoCount === -1) {
        store.commit("mRouter/setDirection", "left");
        store.commit("mRouter/pushHistoryRouter", this.history.current);
        lPush.call(this, location, onComplete, onAbort);
      } else {
        store.commit("mRouter/setDirection", "right");
        //返回
        this.go(lGoCount - mRouter.historyRouter.length);
      }
    };

    // 判断历史记录中是否存在将要跳转的路由，如果有，执行回退操作
    Router.prototype.havRouterHistory = function (location) {
      let lPath = getPath(location);
      return mRouter.historyRouter.findIndex((item) => item.path === lPath);
    };

    // 重写 Router 本身的 go方法，回退的同时要清空记录中的数据
    let lGo = Router.prototype.go;
    Router.prototype.go = function (n) {
      if (n > 0) {
        store.commit("mRouter/setDirection", "left");
        lGo.call(this, n);
        return;
      } else {
        store.commit("mRouter/setDirection", "right");
        store.commit("mRouter/spliceHistoryRouter", [
          mRouter.historyRouter.length + n,
          0 - n - 1,
        ]);
        lGo.call(this, n);
      }
    };

    // 浏览器回退时，清除最后一条路由数据 在layout中监听window的popstate事件时调用
    Router.prototype.delLastRouter = function () {
      store.commit("mRouter/popHistoryRouter");
    };
  },
};
